import { SYSTEM_KEY } from '@/constants/global.const';

class LocalStorageService {
  private static instance: LocalStorageService;

  public static getInstance() {
    if (!LocalStorageService.instance) {
      LocalStorageService.instance = new LocalStorageService();
    }
    return LocalStorageService.instance;
  }

  static makeKey = (key: string): string => {
    let retKey = key;
    if (typeof retKey !== 'string') {
      // eslint-disable-next-line no-console
      console.warn(`${key} used as a key, but it is not a string.`);
      retKey = String(key);
    }
    return `${SYSTEM_KEY}_${retKey}`;
  };

  set = (key: string, value: any) => {
    let retValue = value;
    if (retValue === undefined) {
      retValue = null;
    }
    return window.localStorage.setItem(LocalStorageService.makeKey(key), JSON.stringify(retValue));
  };

  get = (key: string): any => {
    const orgData = window.localStorage.getItem(LocalStorageService.makeKey(key));
    if (orgData === null || typeof orgData === 'undefined') {
      return orgData;
    }
    return JSON.parse(orgData);
  };

  delete = (key: string) => window.localStorage.removeItem(LocalStorageService.makeKey(key));

  clear = () => window.localStorage.clear();
}

export default LocalStorageService.getInstance();
